package myapps.ttclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.WindowManager;

public class Helper {
	public static void WriteStringToDataOutputStream(DataOutputStream dos,String str) 
			throws IOException {
		byte[] ba_str = str.getBytes("UTF-16LE");
		int n = ba_str.length;
		dos.writeInt(n);

		if(n > 0) {
			dos.write(ba_str);
		}
	}

	public static String ParseAsString(DataInputStream dis) throws IOException {
		int n = dis.readInt();
		
		byte[] buffer = new byte[n];

		if(n > 0) {	
			for (int i = 0; i < n; i++) {
				buffer[i] = dis.readByte();
			}
		} else {
			return "";
		}

		return new String(buffer, "UTF-16LE");	
	}

	public static void WriteByteArrayToDataOutputStream(DataOutputStream dos, byte[] data) 
			throws IOException {
		if(data.length > 0) {
			dos.writeInt(data.length);
			dos.write(data);
			
		} else {
			throw new IOException("length <= 0");
		}
	}

	public static byte[] ParseAsByteArray(DataInputStream dis) throws IOException {
		int n = dis.readInt();

		if(n > 0) {	
			byte[] buffer = new byte[n];

			for (int i = 0; i < n; i++) {
				buffer[i] = dis.readByte();
			}

			return buffer;
			
		} else {
			throw new IOException("length <= 0");
		}
	}
	
	public static void ShowNoticeDialog(Context context, String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		builder
		.setTitle(title)
		.setMessage(message)
		.setCancelable(false)
		.setPositiveButton("Close", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}
	
	public static String getName(String path) {
		try {
			int firstindex = path.indexOf('\\');
			int lastindex = path.lastIndexOf('\\');
			
			if(firstindex == lastindex && lastindex == path.length() - 1) {
				//Drive
				return path;
			} else {
				return path.substring(lastindex + 1);
			}
		} catch(Exception ex) {
			return null;
		}
	}
	
	public static void updateFullscreenStatus(Activity activity, Boolean bUseFullscreen) {   
		if(bUseFullscreen) {
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			
		} else {
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			
		}
	}
	
	public static void keepScreenOn(Activity activity) {   
		activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}
}
